﻿// JavaScript Document

// Variables
var _globalCallBack = new Object();
var _firstLoad = true;
var _splitContainer;
var _mouseOffSetX;
var IE = document.all ? true : false;
var _eventUtil = new Object;
var _leftSplitter;
var _rightSplitter;
var _leftPanel;
var _middlePanel;
var _rightPanel;
var _toolBar;
var _viewerTabPage;

var _currentBodyWidth;
var _currentBodyHeight;

var _alertTimerId = 0;
var _leftSplitterLockLeft = -1;
var _leftSplitterLockRight = -1;
var _rightSplitterLockLeft = -1;
var _rightSplitterLockRight = -1;
var _leftPanMinWidth = 250;
var _middlePanMinWidth = 250;
var _rightPanMinWidth = 250;

var _tabManager;

var _treeViewListItemHeight = 22;

var _listItemToPageObj = new Array();

// JSON Parser

/*
http://www.JSON.org/json2.js
2010-03-20

Public Domain.

NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

See http://www.JSON.org/js.html


This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html

USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.


This file creates a global JSON object containing two methods: stringify
and parse.

JSON.stringify(value, replacer, space)
value       any JavaScript value, usually an object or array.

replacer    an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.

space       an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.

This method produces a JSON text from a JavaScript value.

When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value

For example, this would serialize Dates as ISO strings.

Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}

return this.getUTCFullYear()   + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate())      + 'T' +
f(this.getUTCHours())     + ':' +
f(this.getUTCMinutes())   + ':' +
f(this.getUTCSeconds())   + 'Z';
};

You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.

If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.

Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.

The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.

If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.

Example:

text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'


text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'


JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.

The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.

Example:

// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.

myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});

myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});


This is a reference implementation. You are free to copy, modify, or
redistribute.
*/

/*jslint evil: true, strict: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

        // If the string contains no control characters, no quote characters, and no
        // backslash characters, then we can safely slap some quotes around it.
        // Otherwise we must also replace the offending characters with safe escape
        // sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

        // Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

        // If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

        // If we were called with a replacer function, then call the replacer to
        // obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

        // What happens next depends on the value's type.

        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

                // JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

                // If the value is a boolean or null, convert it to a string. Note:
                // typeof null does not produce 'null'. The case is included here in
                // the remote chance that this gets fixed someday.

                return String(value);

                // If the type is 'object', we might be dealing with an object or an array or
                // null.

            case 'object':

                // Due to a specification blunder in ECMAScript, typeof null is 'object',
                // so watch out for that case.

                if (!value) {
                    return 'null';
                }

                // Make an array to hold the partial results of stringifying this object value.

                gap += indent;
                partial = [];

                // Is the value an array?

                if (Object.prototype.toString.apply(value) === '[object Array]') {

                    // The value is an array. Stringify every element. Use null as a placeholder
                    // for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    // Join all of the elements together, separated with commas, and wrap them in
                    // brackets.

                    v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                // If the replacer is an array, use it to select the members to be stringified.

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {

                    // Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

                // Join all of the member texts together, separated with commas,
                // and wrap them in braces.

                v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }

    // If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

            // The stringify method takes a value and an optional replacer, and an optional
            // space parameter, and returns a JSON text. The replacer can be a function
            // that can replace values, or an array of strings that will select the keys.
            // A default replacer method can be provided. Use of the space parameter can
            // produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

            // If the space parameter is a number, make an indent string containing that
            // many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

                // If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

            // If there is a replacer, it must be a function or an array.
            // Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

            // Make a fake root object containing our value under the key of ''.
            // Return the result of stringifying the value.

            return str('', { '': value });
        };
    }


    // If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

            // The parse method takes a text and an optional reviver function, and returns
            // a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

                // The walk method is used to recursively walk the resulting structure so
                // that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


            // Parsing happens in four stages. In the first stage, we replace certain
            // Unicode characters with escape sequences. JavaScript handles many characters
            // incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

            // In the second stage, we run the text against regular expressions that look
            // for non-JSON patterns. We are especially concerned with '()' and 'new'
            // because they can cause invocation, and '=' because it can cause mutation.
            // But just to be safe, we want to reject all unexpected forms.

            // We split the second stage into 4 regexp operations in order to work around
            // crippling inefficiencies in IE's and Safari's regexp engines. First we
            // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
            // replace all simple value tokens with ']' characters. Third, we delete all
            // open brackets that follow a colon or comma or that begin the text. Finally,
            // we look to see that the remaining characters are only whitespace or ']' or
            // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                // In the third stage we use the eval function to compile the text into a
                // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
                // in JavaScript: it can begin a block or an object literal. We wrap the text
                // in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

                // In the optional fourth stage, we recursively walk the new structure, passing
                // each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
            }

            // If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
} ());


/*
xml2json v 1.1
copyright 2005-2007 Thomas Frank

This program is free software under the terms of the 
GNU General Public License version 2 as published by the Free 
Software Foundation. It is distributed without any warranty.
*/

xml2json = {
    parser: function (xmlcode, ignoretags, debug) {
        if (!ignoretags) { ignoretags = "" };
        xmlcode = xmlcode.replace(/\s*\/>/g, '/>');
        xmlcode = xmlcode.replace(/<\?[^>]*>/g, "").replace(/<\![^>]*>/g, "");
        if (!ignoretags.sort) { ignoretags = ignoretags.split(",") };
        var x = this.no_fast_endings(xmlcode);
        x = this.attris_to_tags(x);
        x = escape(x);
        x = x.split("%3C").join("<").split("%3E").join(">").split("%3D").join("=").split("%22").join("\"");
        for (var i = 0; i < ignoretags.length; i++) {
            x = x.replace(new RegExp("<" + ignoretags[i] + ">", "g"), "*$**" + ignoretags[i] + "**$*");
            x = x.replace(new RegExp("</" + ignoretags[i] + ">", "g"), "*$***" + ignoretags[i] + "**$*")
        };
        x = '<JSONTAGWRAPPER>' + x + '</JSONTAGWRAPPER>';
        this.xmlobject = {};
        var y = this.xml_to_object(x).jsontagwrapper;
        if (debug) { y = this.show_json_structure(y, debug) };
        return y
    },
    xml_to_object: function (xmlcode) {
        var x = xmlcode.replace(/<\//g, "§");
        x = x.split("<");
        var y = [];
        var level = 0;
        var opentags = [];
        for (var i = 1; i < x.length; i++) {
            var tagname = x[i].split(">")[0];
            opentags.push(tagname);
            level++
            y.push(level + "<" + x[i].split("§")[0]);
            while (x[i].indexOf("§" + opentags[opentags.length - 1] + ">") >= 0) { level--; opentags.pop() }
        };
        var oldniva = -1;
        var objname = "this.xmlobject";
        for (var i = 0; i < y.length; i++) {
            var preeval = "";
            var niva = y[i].split("<")[0];
            var tagnamn = y[i].split("<")[1].split(">")[0];
            tagnamn = tagnamn.toLowerCase();
            var rest = y[i].split(">")[1];
            if (niva <= oldniva) {
                var tabort = oldniva - niva + 1;
                for (var j = 0; j < tabort; j++) { objname = objname.substring(0, objname.lastIndexOf(".")) }
            };
            objname += "." + tagnamn;
            var pobject = objname.substring(0, objname.lastIndexOf("."));
            if (eval("typeof " + pobject) != "object") { preeval += pobject + "={value:" + pobject + "};\n" };
            var objlast = objname.substring(objname.lastIndexOf(".") + 1);
            var already = false;
            for (k in eval(pobject)) { if (k == objlast) { already = true } };
            var onlywhites = true;
            for (var s = 0; s < rest.length; s += 3) {
                if (rest.charAt(s) != "%") { onlywhites = false }
            };
            if (rest != "" && !onlywhites) {
                if (rest / 1 != rest) {
                    rest = "'" + rest.replace(/\'/g, "\\'") + "'";
                    rest = rest.replace(/\*\$\*\*\*/g, "</");
                    rest = rest.replace(/\*\$\*\*/g, "<");
                    rest = rest.replace(/\*\*\$\*/g, ">")
                }
            }
            else { rest = "{}" };
            if (rest.charAt(0) == "'") { rest = 'unescape(' + rest + ')' };
            if (already && !eval(objname + ".sort")) { preeval += objname + "=[" + objname + "];\n" };
            var before = "="; after = "";
            if (already) { before = ".push("; after = ")" };
            var toeval = preeval + objname + before + rest + after;
            eval(toeval);
            if (eval(objname + ".sort")) { objname += "[" + eval(objname + ".length-1") + "]" };
            oldniva = niva
        };
        return this.xmlobject
    },
    show_json_structure: function (obj, debug, l) {
        var x = '';
        if (obj.sort) { x += "[\n" } else { x += "{\n" };
        for (var i in obj) {
            if (!obj.sort) { x += i + ":" };
            if (typeof obj[i] == "object") {
                x += this.show_json_structure(obj[i], false, 1)
            }
            else {
                if (typeof obj[i] == "function") {
                    var v = obj[i] + "";
                    //v=v.replace(/\t/g,"");
                    x += v
                }
                else if (typeof obj[i] != "string") { x += obj[i] + ",\n" }
                else { x += "'" + obj[i].replace(/\'/g, "\\'").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r") + "',\n" }
            }
        };
        if (obj.sort) { x += "],\n" } else { x += "},\n" };
        if (!l) {
            x = x.substring(0, x.lastIndexOf(","));
            x = x.replace(new RegExp(",\n}", "g"), "\n}");
            x = x.replace(new RegExp(",\n]", "g"), "\n]");
            var y = x.split("\n"); x = "";
            var lvl = 0;
            for (var i = 0; i < y.length; i++) {
                if (y[i].indexOf("}") >= 0 || y[i].indexOf("]") >= 0) { lvl-- };
                tabs = ""; for (var j = 0; j < lvl; j++) { tabs += "\t" };
                x += tabs + y[i] + "\n";
                if (y[i].indexOf("{") >= 0 || y[i].indexOf("[") >= 0) { lvl++ }
            };
            if (debug == "html") {
                x = x.replace(/</g, "&lt;").replace(/>/g, "&gt;");
                x = x.replace(/\n/g, "<BR>").replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;")
            };
            if (debug == "compact") { x = x.replace(/\n/g, "").replace(/\t/g, "") }
        };
        return x
    },
    no_fast_endings: function (x) {
        x = x.split("/>");
        for (var i = 1; i < x.length; i++) {
            var t = x[i - 1].substring(x[i - 1].lastIndexOf("<") + 1).split(" ")[0];
            x[i] = "></" + t + ">" + x[i]
        };
        x = x.join("");
        return x
    },
    attris_to_tags: function (x) {
        var d = ' ="\''.split("");
        x = x.split(">");
        for (var i = 0; i < x.length; i++) {
            var temp = x[i].split("<");
            for (var r = 0; r < 4; r++) { temp[0] = temp[0].replace(new RegExp(d[r], "g"), "_jsonconvtemp" + r + "_") };
            if (temp[1]) {
                temp[1] = temp[1].replace(/'/g, '"');
                temp[1] = temp[1].split('"');
                for (var j = 1; j < temp[1].length; j += 2) {
                    for (var r = 0; r < 4; r++) { temp[1][j] = temp[1][j].replace(new RegExp(d[r], "g"), "_jsonconvtemp" + r + "_") }
                };
                temp[1] = temp[1].join('"')
            };
            x[i] = temp.join("<")
        };
        x = x.join(">");
        x = x.replace(/ ([^=]*)=([^ |>]*)/g, "><$1>$2</$1");
        x = x.replace(/>"/g, ">").replace(/"</g, "<");
        for (var r = 0; r < 4; r++) { x = x.replace(new RegExp("_jsonconvtemp" + r + "_", "g"), d[r]) };
        return x
    }
};


if (!Array.prototype.push) {
    Array.prototype.push = function (x) {
        this[this.length] = x;
        return true
    }
};

if (!Array.prototype.pop) {
    Array.prototype.pop = function () {
        var response = this[this.length - 1];
        this.length--;
        return response
    }
};


// End JSON Parser

// Initiators
if (!IE) { document.captureEvents(Event.MOUSEMOVE) }

// Fix the lack of Array.indexOf in IE.
if (!Array.indexOf) {
    Array.prototype.indexOf = function (obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

_eventUtil.ApplyHandler = function (target, fn, e) {
    if (!e) e = window.event;

    if (Function.prototype.call) {
        fn.call(target, e);
    } else {
        target.__ElementApply = fn;
        target.__ElementApply(e)
    }
}

_eventUtil.addEventHandler = function (oTarget, sEventType, fnHandler) {
    if (oTarget.addEventListener) {
        oTarget.addEventListener(sEventType, fnHandler, false);
    } else {
        var originalHandler = oTarget["on" + sEventType];
        if (originalHandler) {
            oTarget["on" + sEventType] = function (e) {
                _eventUtil.ApplyHandler(this, originalHandler, e);
                _eventUtil.ApplyHandler(this, fnHandler, e);
            };
        } else {
            oTarget["on" + sEventType] = function (e) {
                _eventUtil.ApplyHandler(this, fnHandler, e)
            };
        }
    }

};
_eventUtil.removeEventHandler = function (oTarget, sEventType, fnHandler) {
    if (oTarget.removeEventListener) {
        oTarget.removeEventListener(sEventType, fnHandler, false);
    } else {
        oTarget["on" + sEventType] = null;
    }
};

function GetElementById(nodeToSearch, id) {

    var result = null;

    if (nodeToSearch.getAttribute('id') == id)
        return nodeToSearch;

    for (var i = 0; i < nodeToSearch.childNodes.length; i++) {
        if (nodeToSearch.childNodes[i].nodeType == 1) {
            result = GetElementById(nodeToSearch.childNodes[i], id);
            if (result != null)
                break;
        }
    }

    return result;
}

window.onload = function () {
    // Set up Objects so that we can use them globaly.
    _leftPanel = new Element(document.getElementById('uiLeft'), 'panel');
    _middlePanel = new Element(document.getElementById('uiMain'), 'panel');
    _rightPanel = new Element(document.getElementById('uiRight'), 'panel');
    _toolBar = new Element(document.getElementById('toolBar'), 'toolbar');
    _viewerTabPage = new Element(document.getElementById('viewer'), 'tabPage');

    _leftSplitter = new Element(document.getElementById('leftSplitter'), 'splitter');
    _rightSplitter = new Element(document.getElementById('rightSplitter'), 'splitter');

    _tabManager = new TabManager(document.getElementById('tabList'));
    _tabManager.tabHCssClassSel = 'sel';
    _tabManager.tabHLeftClass = 'tabL';
    _tabManager.tabHRightClass = 'tabR';
    _tabManager.tabHMidClass = 'tabM';
    _tabManager.tabListH.element.className = 'clearfix';
    _tabManager.setContainerVClassName('vTabList');

    // Initial Resize of the display
    window.onresize = function () {
        // Resize Page Elements
        ResizeDisplay();
        clearTimeout(_alertTimerId);
        _alertTimerId = setTimeout("ResizeDisplay()", 125);
    };
    _leftSplitter.element.onmouseover = function () {
        _leftSplitter.element.style.cursor = 'E-resize';
    };
    _rightSplitter.element.onmouseover = function () {
        _rightSplitter.element.style.cursor = 'E-resize';
    };
    _leftSplitter.element.onmousedown = function (e) {
        setSplitterOnMove(e, 'leftSplitter');
    };
    _rightSplitter.element.onmousedown = function (e) {
        setSplitterOnMove(e, 'rightSplitter');
    };

    setTimeout("ResizeDisplay()", 125);
};

function LoadFeed(URL, ElementID, LoadingHTML, callBackMethod, submitMethod) {
    var randNum = Math.floor(Math.random() * 99999999999999999);
    var XMLObject;

    if (submitMethod == 'undefined')
        submitMethod = 'GET';

    _globalCallBack[randNum] = callBackMethod;

    XMLObject = false;

    if (window.XMLHttpRequest && !(window.ActiveXObject)) {
        try {
            XMLObject = new XMLHttpRequest();
        } catch (e) {
            XMLObject = false;
        }
    } else if (window.ActiveXObject) {

        try {
            XMLObject = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                XMLObject = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                XMLObject = false;
            }
        }
    }

    if (XMLObject) {
        if (ElementID != '') {
            document.getElementById(ElementID).innerHTML = LoadingHTML;
        }

        var params;

        if (submitMethod == 'POST') {
            params = URL.split('?')[1]
            XMLObject.open("POST", URL.split('?')[0] + '?Rndd=' + randNum, true);

            XMLObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            XMLObject.setRequestHeader("Content-length", params.length);
            XMLObject.setRequestHeader("Connection", "close");
        }
        else {
            if (URL.indexOf('?') == -1) {
                XMLObject.open("GET", URL + '?Rndd=' + randNum, true);
            } else {
                XMLObject.open("GET", URL + '&Rndd=' + randNum, true);
            }
        }

        XMLObject.onreadystatechange = function () {
            if (XMLObject.readyState == 4 && XMLObject.status == 200) {
                var XML = XMLObject.responseXML;
                var functionID = XML.getElementsByTagName('functionID')[0].firstChild.nodeValue;

                var XMLDoc;
                if (XML.getElementsByTagName('JSON')[0].firstChild.nodeValue != '')
                    XMLDoc = JSON.parse(XML.getElementsByTagName('JSON')[0].firstChild.nodeValue);
                else
                    XMLDoc = '';

                var f = _globalCallBack[functionID];
                XMLObject = null;

                delete _globalCallBack[functionID];

                f(XMLDoc, ElementID);
            }
        };

        if (submitMethod == 'POST')
            XMLObject.send(params);
        else
            XMLObject.send("");
    } else {
        document.getElementById(ElementID).innerHTML = '<div class="errordiv">No LDAP detected</div>';
    }

}

// Objects
function Element(o, type) {
    this.element = o;
    this.type = type;
    this.widthT = function () {
        return this.element.offsetWidth +
                getCurrentStyle(this.element, 'margin-left', 'marginLeft') +
                getCurrentStyle(this.element, 'margin-right', 'marginRight');
    }
    this.heightT = function () {
        return this.element.offsetHeight +
                getCurrentStyle(this.element, 'margin-top', 'marginTop') +
                getCurrentStyle(this.element, 'margin-bottom', 'marginBottom');
    }
    this.widthEx = function () {
        return getCurrentStyle(this.element, 'padding-left', 'paddingLeft') +
               getCurrentStyle(this.element, 'padding-right', 'paddingRight') +
               getCurrentStyle(this.element, 'margin-left', 'marginLeft') +
               getCurrentStyle(this.element, 'margin-right', 'marginRight') +
               getCurrentStyle(this.element, 'border-left-width', 'borderLeftWidth') +
               getCurrentStyle(this.element, 'border-right-width', 'borderRightWidth');
    }
    this.heightEx = function () {
        return getCurrentStyle(this.element, 'padding-top', 'paddingTop') +
               getCurrentStyle(this.element, 'padding-bottom', 'paddingBottom') +
               getCurrentStyle(this.element, 'margin-top', 'marginTop') +
               getCurrentStyle(this.element, 'margin-bottom', 'marginBottom') +
               getCurrentStyle(this.element, 'border-top-width', 'borderTopWidth') +
               getCurrentStyle(this.element, 'border-bottom-width', 'borderBottomWidth');
    }
    this.left = function () {
        return getCurrentStyle(this.element, 'left', 'left');
    }
    this.right = function () {
        return getCurrentStyle(this.element, 'right', 'right');
    }
    this.top = function () {
        return getCurrentStyle(this.element, 'top', 'top');
    }
    this.bottom = function () {
        return getCurrentStyle(this.element, 'bottom', 'bottom');
    }
    this.width = function () {
        return this.element.offsetWidth;
    }
    this.height = function () {
        return this.element.offsetHeight;
    }
    this.removeAllChildren = function () {
        while (this.element.childNodes.length >= 1) {
            this.element.removeChild(this.element.firstChild);
        }
    }
    this.removeElement = function () {
        if (this.element.parentNode)
            this.element.parentNode.removeChild(this.element);
    }
}

function DisposeObj(obj) {
    obj = null;
}

function TabManager(container) {
    var _firstDropDownIndex = -1;
    var _extraTabs = false;
    var _tabManager = this;

    this.tabs = new Array();
    this.tabListH = new Element(document.createElement('ul'), 'tabListH');
    this.listContainerV = new Element(document.createElement('div'), 'tabDivV');
    this.tabListV = new Element(document.createElement('ul'), 'tabListV');
    this.selectedTab = null;

    this.listContainerV.element.appendChild(this.tabListV.element);

    this.tabHCssClassSel = '';
    this.tabHCssClassDeSel = '';
    this.tabHLeftClass = '';
    this.tabHRightClass = '';
    this.tabHMidClass = '';
    this.tabHIconClass = '';
    this.tabHTextClass = '';

    this.tabVCssClassSel = '';
    this.tabVCssClassDeSel = '';
    this.tabVLeftClass = '';
    this.tabVRightClass = '';
    this.tabVMidClass = '';
    this.tabVIconClass = '';
    this.tabVTextClass = '';

    this.containerV = new Element(document.createElement('div'), 'tabContainerV');

    this.container = new Element(container, 'tabContainerH');
    this.container.element.innerHTML = '';

    this.container.element.appendChild(this.tabListH.element);
    this.container.element.appendChild(this.containerV.element);

    this.setContainerVClassName = function (className) {
        this.containerV.element.className = className;
    }

    this.addTab = function (id, type, text, objOwner) {
        var newTab = this.checkTabs(id, type, text, objOwner);

        if (newTab == null) {
            newTab = new Tab(type, text, id);
            newTab.owner = this;
            newTab.setupTab();
            newTab.objectOwner = objOwner;
            newTab.objectOwner.page.loadPage();
            _eventUtil.addEventHandler(newTab.listItem.element, 'click', newTab.SelectEvent);
            this.tabs.unshift(newTab);
        }

        newTab.Select();
    }
    this.removeTab = function (removeTab) {
        var index = this.tabs.indexOf(removeTab);
        if (index != -1)
            this.tabs.splice(index, 1);
    }

    this.checkTabs = function (id, type, text) {
        for (var i = 0; i < this.tabs.length; i++) {
            if (this.tabs[i].id == id && this.tabs[i].type == type && this.tabs[i].text == text)
                return this.tabs[i];
        }

        return null;
    }

    this.reDraw = function () {

        var tempWidth = this.tabListH.widthEx();
        this.containerV.element.style.display = 'none';

        if (_extraTabs) {
            this.containerV.element.style.display = 'block';
            tempWidth += this.containerV.widthT();
        }

        _firstDropDownIndex = -1;

        if (this.tabListH.element.hasChildNodes()) {
            while (this.tabListH.element.childNodes.length >= 1) {
                this.tabListH.element.removeChild(this.tabListH.element.firstChild);
            }
        }

        for (var t = 0; t < this.tabs.length; t++) {
            _eventUtil.removeEventHandler(this.tabs[t].listItem.element, 'mouseover', this.tabListVItemHover);
            _eventUtil.removeEventHandler(this.tabs[t].listItem.element, 'mouseout', this.tabListVItemOut);

            if (this.tabs[t].selected) {
                this.tabs[t].listItem.element.className = this.tabHCssClassSel;
                this.tabs[t].objectOwner.page.pageDisplay.element.style.display = 'block';
            } else {
                this.tabs[t].listItem.element.className = this.tabHCssClassDeSel;
                this.tabs[t].objectOwner.page.pageDisplay.element.style.display = 'none';
            }

            this.tabs[t].listItem.element.className += ' fl-left';
            this.tabs[t].setTabHClassNames();

            this.tabListH.element.appendChild(this.tabs[t].listItem.element);
            tempWidth += this.tabs[t].listItem.widthT();

            if (tempWidth > this.container.widthT() - this.container.widthEx()) {
                if (!this.checkSelected(t)) {
                    tempWidth -= this.tabs[t].listItem.widthT();
                    this.tabListH.element.removeChild(this.tabs[t].listItem.element);
                    _firstDropDownIndex = t;

                    if (!_extraTabs) {
                        _extraTabs = true;
                        this.reDraw();
                    }
                }

                break;
            }

        }

        if (_extraTabs) {
            _extraTabs = false;
            this.reDrawDrop();
        }
    }

    this.reDrawDrop = function () {
        this.listContainerV.element.style.position = 'absolute';
        this.listContainerV.element.style.left = '0px';
        this.listContainerV.element.style.top = '16px';
        this.listContainerV.element.style.border = '1px solid #000';
        this.listContainerV.element.style.display = 'none';
        this.listContainerV.element.style.zIndex = '99';
        this.listContainerV.element.style.width = '150px';
        this.tabListV.element.innerHTML = '';

        for (var i = _firstDropDownIndex; i < this.tabs.length; i++) {
            if (this.checkSelected(i))
                return;

            this.tabs[i].setTabVClassNames();
            _eventUtil.addEventHandler(this.tabs[i].listItem.element, 'mouseover', this.tabListVItemHover);
            _eventUtil.addEventHandler(this.tabs[i].listItem.element, 'mouseout', this.keepShowingDrop);
            _eventUtil.addEventHandler(this.tabs[i].listItem.element, 'mouseout', this.tabListVItemOut);
            this.tabListV.element.appendChild(this.tabs[i].listItem.element);
        }

        this.containerV.element.innerHTML = '';
        this.containerV.element.appendChild(this.listContainerV.element);
    }

    this.checkSelected = function (index) {
        if (this.tabs[index].selected && index != 0) {
            var tempTab = this.tabs[index];
            this.tabs.splice(this.tabs.indexOf(tempTab), 1);
            this.tabs.unshift(tempTab);
            this.reDraw();
            return true;
        }

        return false;
    }

    this.tabListVItemHover = function () {
        this.style.backgroundColor = '#ff0000';
    }

    this.tabListVItemOut = function () {
        this.style.backgroundColor = '';
    }

    this.keepShowingDrop = function (e) {
        if (e.stopPropagation) { e.stopPropagation(); }
        StopFurtherAction(e);
    }

    this.showDropMenu = function () {
        this.getElementsByTagName('div')[0].style.display = 'block';
        _inVerticalDrop = 1;
    }

    this.hideDropMenu = function (e) {
        this.style.display = 'none';
        if (e.stopPropagation) { e.stopPropagation(); }
        StopFurtherAction(e);
    }

    this.dispose = function () {
        var tabManager = _tabManager;

        for (var i = 0; i < tabManager.tabs.length; i++) {
            tabManager.tabs[i].dispose();
        }

        _eventUtil.removeEventHandler(tabManager.tabListV.element, 'mouseout', tabManager.keepShowingDrop);
        _eventUtil.removeEventHandler(tabManager.containerV.element, 'click', tabManager.showDropMenu);
        _eventUtil.removeEventHandler(tabManager.listContainerV.element, 'mouseout', tabManager.hideDropMenu);

        tabManager.container.removeElement();

        DisposeObj(tabManager);
    }

    _eventUtil.addEventHandler(this.tabListV.element, 'mouseout', this.keepShowingDrop);
    _eventUtil.addEventHandler(this.containerV.element, 'click', this.showDropMenu);
    _eventUtil.addEventHandler(this.listContainerV.element, 'mouseout', this.hideDropMenu);
}

function Tab(type, text, id) {
    var _tab = this;

    var _tabL = document.createElement('span');
    var _tabM = document.createElement('span');
    var _tabR = document.createElement('span');
    var _icon = document.createElement('img');
    var _displayText = document.createElement('span');
    var _closeIcon = document.createElement('img');

    _closeIcon.src = '/images/tabs/close.png';
    _closeIcon.className = 'close';

    this.id;
    this.text;
    this.type;
    this.owner = null;
    this.selected = false;
    this.listIndex = -1;
    this.listItem = new Element(document.createElement('li'), 'tab');
    this.objectOwner = null;

    this.listItem.element.appendChild(_tabL);
    this.listItem.element.appendChild(_tabM);
    this.listItem.element.appendChild(_tabR);

    _tabM.appendChild(_icon);
    _tabM.appendChild(_displayText);
    _tabM.appendChild(_closeIcon);

    this.setTabHClassNames = function () {
        _tabL.className = this.owner.tabHLeftClass;
        _tabR.className = this.owner.tabHRightClass;
        _tabM.className = this.owner.tabHMidClass;
        _icon.className = this.owner.tabHIconClass;
        _displayText.className = this.owner.tabHTextClass;
    }

    this.setTabVClassNames = function () {
        _tabL.className = this.owner.tabVLeftClass;
        _tabR.className = this.owner.tabVRightClass;
        _tabM.className = this.owner.tabVMidClass;
        _icon.className = this.owner.tabVIconClass;
        _displayText.className = this.owner.tabVTextClass;
    }

    this.SelectEvent = function () {
        var tab = _tab;
        tab.Select();
    }

    this.Select = function () {

        if (this.owner.selectedTab != null)
            this.owner.selectedTab.selected = false;

        this.selected = true;
        this.owner.selectedTab = this;
        this.owner.reDraw();
    }

    this.setType = function (newType) {
        var iconName;

        this.type = newType;

        switch (this.type) {
            case "template":
                iconName = "page_html.gif";
                break;
            case "basepage":
                iconName = "page_offline.gif";
                break;
            case "csssnippet":
                iconName = "page_online.gif";
                break;
        }
        _icon.src = '/images/' + iconName;
    }
    this.setText = function (newText) {
        this.text = newText;
        _displayText.innerHTML = this.text;
    }
    this.setId = function (newId) {
        this.id = newId

        this.listItem.element.id = '$$Tab$$' + this.id;
    }

    this.setupTab = function () {
        this.setText(text);
        this.setType(type);
        this.setId(id);
    }

    this.dispose = function () {
        var tab = _tab;

        _eventUtil.removeEventHandler(tab.listItem.element, 'mouseover', tab.owner.tabListVItemHover);
        _eventUtil.removeEventHandler(tab.listItem.element, 'mouseout', tab.owner.keepShowingDrop);
        _eventUtil.removeEventHandler(tab.listItem.element, 'mouseout', tab.owner.tabListVItemOut);
        _eventUtil.removeEventHandler(tab.listItem.element, 'click', tab.SelectEvent);
        _eventUtil.removeEventHandler(_closeIcon, 'click', tab.dispose);

        tab.objectOwner.page.disposeDisplay();
        tab.owner.removeTab(tab);
        tab.listItem.removeElement();

        DisposeObj(tab);
    }

    _eventUtil.addEventHandler(_closeIcon, 'click', this.dispose);
}

function Page(type, id) {
    var _page = this;

    this.type;
    this.id;
    this.owner = null;
    this.pageDisplay;
    this.tabManager;
    this.listManager;

    this.setType = function (newType) {
        this.type = newType;
    }

    this.setId = function (newId) {
        this.id = newId;
    }

    this.loadPage = function () {
        var _job;

        switch (this.type) {
            case "template":
            case "basepage":
            case "csssnippet":
                this.pageDisplay = new Element(document.getElementById('genPageSetup').cloneNode(true), 'page');
                this.pageDisplay.element.id = this.type + 'PageSetup_' + this.id;
                GetElementById(this.pageDisplay.element, 'genContainer').id = this.type + 'versionContainer_' + this.id;
                GetElementById(this.pageDisplay.element, 'genContainerForm').id = this.type + 'versionContainerForm_' + this.id;
                GetElementById(this.pageDisplay.element, 'genPageTabList').id = this.type + 'PageTabList_' + this.id;
                GetElementById(this.pageDisplay.element, 'genPageViewer').id = this.type + 'PageViewer_' + this.id;
                this.tabManager = new TabManager(GetElementById(this.pageDisplay.element, this.type + 'PageTabList_' + this.id));
                this.tabManager.tabHCssClassSel = 'sel';
                this.tabManager.tabHLeftClass = 'tabL';
                this.tabManager.tabHRightClass = 'tabR';
                this.tabManager.tabHMidClass = 'tabM';
                this.tabManager.tabListH.element.className = 'clearfix';
                this.listManager = new ListManager(GetElementById(this.pageDisplay.element, this.type + 'versionContainerForm_' + this.id), this.type + 'version');
                _viewerTabPage.element.appendChild(this.pageDisplay.element);
                _job = "load-" + this.type + "-versions&ID=" + this.id;
                break;
            case "templateversion":
            case "basepageversion":
            case "csssnippetversion":
                var tempType = this.type.split('version')[0];
                this.pageDisplay = new Element(document.getElementById(tempType + 'PageVersionSetup').cloneNode(true), 'pageVersion');
                this.pageDisplay.element.id = tempType + 'PageVersionSetup_' + this.id;
                GetElementById(this.pageDisplay.element, tempType + 'Form').id = tempType + 'Form_' + this.id;
                document.getElementById(tempType + 'PageViewer_' + this.id.split('_')[0]).appendChild(this.pageDisplay.element);
                _job = "load-" + this.type + "&ID=" + this.id.split('_')[0] + "&versionNo=" + this.id.split('_')[1];
        }

        LoadFeed('/runjob.aspx?job=' + _job, '', '', this.setPage);
    }

    this.setPage = function (XMLDoc, ElementID) {
        var page = _page;

        switch (page.type) {
            case "template":
            case "basepage":
            case "csssnippet":
                for (var v = 0; v < XMLDoc.versions.length; v++) {
                    page.listManager.addListItem(page.id + '_' + XMLDoc.versions[v].version, XMLDoc.versions[v].version + '<input type="checkbox" name="live" value="live" onclick="uncheckAllButThis(\'' + page.type + 'versionContainerForm_' + page.id + '\', this, event)"/>');
                    _listItemToPageObj[page.id + '_' + XMLDoc.versions[v].version] = page;
                }
                break;
            case "templateversion":
                if (XMLDoc.template.name) {
                    var form = page.pageDisplay.element.getElementsByTagName('form')[0];

                    form.id = '$$form$$' + page.id;
                    form.elements['templateName'].value = XMLDoc.template.name == undefined ? '' : XMLDoc.template.name;
                    form.elements['template'].value = XMLDoc.template.template == undefined ? '' : page.reFormatCode(XMLDoc.template.template);
                    form.elements['js'].value = XMLDoc.template.javascript == undefined ? '' : page.reFormatCode(XMLDoc.template.javascript);
                }
                break;
            case "basepageversion":
                if (XMLDoc.basePage.name) {
                    var form = page.pageDisplay.element.getElementsByTagName('form')[0];

                    form.id = '$$form$$' + page.id;
                    form.elements['pageName'].value = XMLDoc.basePage.name == undefined ? '' : XMLDoc.basePage.name;
                    form.elements['title'].value = XMLDoc.basePage.title == undefined ? '' : XMLDoc.basePage.title;
                    form.elements['metaDesc'].value = XMLDoc.basePage.metaDesc == undefined ? '' : XMLDoc.basePage.metaDesc;
                    form.elements['metaKeywords'].value = XMLDoc.basePage.metaKeyWords == undefined ? '' : XMLDoc.basePage.metaKeyWords;
                    form.elements['favIcon'].value = XMLDoc.basePage.favIcon == undefined ? '' : XMLDoc.basePage.favIcon;
                    form.elements['shortIcon'].value = XMLDoc.basePage.shortcutIcon == undefined ? '' : XMLDoc.basePage.shortcutIcon;

                    var docType = XMLDoc.basePage.docType;

                    for (var opt = 0; opt < form.elements['docType'].options.length; opt++) {
                        if (form.elements['docType'].options[opt].value == docType) {
                            form.elements['docType'].options[opt].selected = true;
                            break;
                        }
                    }

                    GetElementById(form, 'basepagesettingsTab').id = page.type + '_basepagesettingsTab_' + page.id;
                    GetElementById(form, 'basepagesettingsViewer').id = page.type + '_basepagesettingsViewer_' + page.id;
                    GetElementById(form, 'basepagesettingsPreview').id = page.type + '_basepagesettingsPreview_' + page.id;
                    GetElementById(form, 'basepagesettingsSettingsView').id = page.type + '_basepagesettingsSettingsView_' + page.id;
                    GetElementById(form, 'previewObj').id = page.type + '_previewObj_' + page.id;
                    GetElementById(form, 'previewFrame').id = page.type + '_previewFrame_' + page.id;

                    page.tabManager = new TabManager(page.type + '_basepagesettingsTab_' + page.id);

                    LoadFeed('/runjob.aspx?job=set-preview&settingsXML=' + JSONToXML(XMLDoc.basePage.settingsXML).replace(/\?/g, '[CMSQM]').replace(/</g, '[CMSLTS]'), '', '', page.setPreview, 'POST');
                }
                break;
            case "csssnippetversion":
                if (XMLDoc.csssnippet.name) {
                    var form = page.pageDisplay.element.getElementsByTagName('form')[0];

                    form.id = '$$form$$' + page.id;
                    form.elements['cssSnippetName'].value = XMLDoc.csssnippet.name == undefined ? '' : XMLDoc.csssnippet.name;
                    form.elements['cssSnippet'].value = XMLDoc.csssnippet.css == undefined ? '' : page.reFormatCode(XMLDoc.csssnippet.css);
                }
                break;
        }
    }

    this.setPreview = function (XMLDoc, ElementID) {
        if (!IE)
            document.getElementById(_page.type + '_previewObj_' + _page.id).setAttribute('data', '/cmsPreview.aspx');
        else {
            var iframe = document.createElement('iframe');
            iframe.name = _page.type + '_iframe_' + _page.id;
            iframe.src = '/cmsPreview.aspx';
            document.getElementById(_page.type + '_previewFrame_' + _page.id).appendChild(iframe);
            document.getElementById(_page.type + '_previewFrame_' + _page.id).style.display = 'block';
        }
    }

    this.reFormatCode = function (string) {
        var tempString = string.replace(/\[CMSNL\]/g, '\n');
        tempString = tempString.replace(/\[CMSQ\]/g, '"');
        tempString = tempString.replace(/\[CMSSQ\]/g, '\'');
        tempString = tempString.replace(/\[CMSAND\]/g, '&');
        tempString = tempString.replace(/&lt;/g, '<');
        tempString = tempString.replace(/&gt;/g, '>');
        tempString = tempString.replace(/\\\\/g, '\\');
        tempString = tempString.replace(/\\\//g, '\/');

        return tempString;
    }

    this.disposeDisplay = function () {
        if (this.tabManager)
            this.tabManager.dispose();

        if (this.listManager)
            this.listManager.dispose();

        if (this.pageDisplay)
            this.pageDisplay.removeElement();
    }

    this.dispose = function () {
        var page = _page;

        if (page.tabManager)
            page.tabManager.dispose();

        if (page.listManager)
            page.listManager.dispose();

        if (page.pageDisplay)
            page.pageDisplay.removeElement();

        DisposeObj(page);
    }

    this.setType(type);
    this.setId(id);
}

function JSONToXML(jsonObj) {
    var tempString = '<?xml version="1.0" encoding="ISO-8859-1"?>\n';
    tempString += '<OBi xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n';
    tempString += '<page>\n';

    for (var i = 0; i < jsonObj.length; i++) {
        tempString += AddTemplateXML(jsonObj[i]);
    }

    tempString += '</page>';
    tempString += '</OBi>';

    return tempString;
}

function AddTemplateXML(jsonObj) {
    var tempString = '<template name="' + jsonObj.Name + '" id="' + jsonObj.Id + '"';

    if (jsonObj.Children.length > 0)
        tempString += '>\n';
    else
        tempString += '/>\n';

    for (var i = 0; i < jsonObj.Children.length; i++) {
        switch (jsonObj.Children[i].XMLTagName) {
            case "template":
                tempString += AddTemplateXML(jsonObj.Children[i]);
                break;
            case "widget":
                tempString += AddWidgetXML(jsonObj.Children[i]);
                break;
        }
    }

    if (jsonObj.Children.length > 0) {
        tempString += '</template>\n';
    }

    return tempString;
}

function AddWidgetXML(jsonObj) {
    var tempString = '<widget name="' + jsonObj.Name + '" id="' + jsonObj.Id + '" type="' + jsonObj.Type + '"';

    if (jsonObj.WidgetProperties.length > 0)
        tempString += '>\n';
    else
        tempString += '/>\n';

    for (var i = 0; i < jsonObj.WidgetProperties.length; i++) {
        tempString += '<' + jsonObj.WidgetProperties[i].Name + ' ';

        for (var p = 0; p < jsonObj.WidgetProperties[i].ItemProperties.length; p++) {
            tempString += jsonObj.WidgetProperties[i].ItemProperties[p][0] + '="' + jsonObj.WidgetProperties[i].ItemProperties[p][1] + '" ';
        }

        tempString += '/>'
    }

    if (jsonObj.WidgetProperties.length > 0) {
        tempString += '</widget>\n';
    }

    return tempString;
}

function uncheckAllButThis(checkboxGroup, checkBox, e) {
    for (var i = 0; i < document.getElementById(checkboxGroup).live.length; i++) {
        if (document.getElementById(checkboxGroup).live[i] != checkBox)
            document.getElementById(checkboxGroup).live[i].checked = false;
    }

    StopFurtherAction(e);
}

function ListManager(container, type) {
    var _listManager = this;

    this.type = type;
    this.listItems = new Array();
    this.list = new Element(document.createElement('ul'), type + 'list');

    this.container = new Element(container, 'listContainer');
    this.container.element.innerHTML = '';

    this.container.element.appendChild(this.list.element);

    this.setContainerClassName = function (className) {
        this.container.element.className = className;
    }

    this.addListItem = function (id, text) {
        var newListItem = new ListItem(id, this.type, text);
        newListItem.owner = this;
        newListItem.setupNode();
        _eventUtil.addEventHandler(newListItem.listItem.element, 'click', newListItem.SelectEvent);
        this.listItems.push(newListItem);
        this.list.element.appendChild(newListItem.listItem.element);
    }

    this.dispose = function () {
        var listManager = _listManager;
        for (var i = 0; i < listManager.listItems.length; i++) {
            listManager.listItems[i].dispose();
        }

        listManager.list.removeElement();

        DisposeObj(listManager);
    }
}

function ListItem(id, type, text) {
    var _ListItem = this;

    this.id;
    this.text;
    this.type;
    this.owner = null;
    this.listItem = new Element(document.createElement('li'), 'listItem');
    this.page;

    this.setPage = function () {
        this.page = new Page(this.type, this.id);
        this.page.owner = this;
    }

    this.SelectEvent = function (e) {
        var ListItem = _ListItem;
        ListItem.Open();
        if (e.stopPropagation) { e.stopPropagation(); }
        StopFurtherAction(e);
    }

    this.Open = function () {
        switch (this.type) {
            case "basepageversion":
            case "templateversion":
            case "csssnippetversion":
                var page = _listItemToPageObj[this.id];
                page.tabManager.addTab(this.id, this.type, parseInt(this.text), this);
                break;
            default:
                if (this.opened) {
                    this.opened = false;
                }
                else {
                    this.opened = true;
                }

                _manager.reDrawTreeView();
                break;
        }

    }

    this.setType = function (newType) {
        this.type = newType;
    }
    this.setText = function (newText) {
        this.text = newText;
        this.listItem.element.innerHTML = this.text;
    }
    this.setId = function (newId) {
        this.id = newId

        this.listItem.element.id = '$$ListItem$$' + this.id;
    }

    this.setupNode = function () {
        this.setText(text);
        this.setType(type);
        this.setId(id);
        this.setPage();
    }

    this.dispose = function () {
        var listItem = _ListItem;
        listItem.page.dispose();

        _eventUtil.removeEventHandler(listItem.listItem.element, 'click', listItem.SelectEvent);

        listItem.listItem.removeElement();

        DisposeObj(listItem);
    }
}

// Functions
function setSplitterOnMove(e, splitter) {
    e = e || window.event;

    _splitContainer = new Element(document.getElementById(splitter));

    if (IE) { // grab the x-y pos.s if browser is IE
        _mouseOffSetX = e.clientX + document.documentElement.scrollLeft - parseInt(_splitContainer.element.style.left);
    } else {  // grab the x-y pos.s if browser is NS
        _mouseOffSetX = e.pageX - parseInt(_splitContainer.element.style.left);
    }

    document.body.style.cursor = 'col-resize';
    _eventUtil.addEventHandler(document, 'mouseup', removeMouseHandlers);
    _eventUtil.addEventHandler(document, 'mousemove', moveSplitter);

    StopFurtherAction(e);
}

function removeMouseHandlers(e) {
    document.body.style.cursor = 'default';
    _eventUtil.removeEventHandler(document, 'mousemove', moveSplitter);
    _eventUtil.removeEventHandler(document, 'mouseup', removeMouseHandlers);

    StopFurtherAction(e);
}

function moveSplitter(e) {

    var currentmouseX;

    if (IE) {
        // Swaps e to window.event to track mouse.
        e = e || window.event;
        currentmouseX = e.clientX + document.documentElement.scrollLeft;
    } else {
        currentmouseX = e.pageX;
    }

    if (currentmouseX < 0) { currentmouseX = 0; }

    // Which Splitter are we moving.
    if (_splitContainer.element.id == 'leftSplitter') {
        _rightSplitterLockRight = -1;

        // Stop moving the splitter if the user tries to move it past the right splitter.
        if (_splitContainer.widthT() + _splitContainer.left() >= (_rightSplitter.left() - (_middlePanMinWidth + _middlePanel.widthEx())) && _leftSplitterLockRight == -1) {
            _splitContainer.element.style.left = (_rightSplitter.left() - (_middlePanMinWidth + _middlePanel.widthEx() + _splitContainer.widthT())) + 'px';
            _leftSplitterLockRight = _splitContainer.left();
            _leftSplitterLockLeft = -1;
        }
        // Stops the splitter moving less than the left panels min width
        else if ((_splitContainer.left() <= _leftPanel.left() + _leftPanMinWidth) && _leftSplitterLockLeft == -1) {
            _splitContainer.element.style.left = (_leftPanel.left() + _leftPanMinWidth) + 'px';
            _leftSplitterLockLeft = _splitContainer.left();
            _leftSplitterLockRight = -1;
        }
        else if (_leftSplitterLockRight != -1 && currentmouseX < _leftSplitterLockRight) {
            _leftSplitterLockRight = -1;
            _splitContainer.element.style.left = currentmouseX - _mouseOffSetX + 'px';
        }
        else if (_leftSplitterLockRight != -1 && currentmouseX > _leftSplitterLockRight) {
            // Do nothing so the splitter stops moving.
        }
        else if (_leftSplitterLockLeft != -1 && currentmouseX > _leftSplitterLockLeft) {
            _leftSplitterLockLeft = -1;
            _splitContainer.element.style.left = currentmouseX - _mouseOffSetX + 'px';
        }
        else if (_leftSplitterLockLeft != -1 && currentmouseX < _leftSplitterLockLeft) {
            // Do nothing so the splitter stops moving.
        }
        else {
            _splitContainer.element.style.left = currentmouseX - _mouseOffSetX + 'px';
        }

        // Make sure the new widths are not less than it should be.
        // putting this in stops IE8 from crashing when moving the right splitter at a extremely fast rate.

        var leftWidth = _splitContainer.left() - _leftPanel.widthEx();
        var middlePanWidth;

        if (leftWidth < _leftPanMinWidth) leftWidth = _leftPanMinWidth;

        _leftPanel.element.style.width = leftWidth + 'px';
        _middlePanel.element.style.left = (_splitContainer.left() + _splitContainer.widthT()) + 'px';

        middlePanWidth = _rightSplitter.left() - _middlePanel.left() - _middlePanel.widthEx();

        if (middlePanWidth >= _middlePanMinWidth)
            _middlePanel.element.style.width = (middlePanWidth) + 'px';
        else
            _middlePanel.element.style.width = _middlePanMinWidth + 'px';

    }
    else {
        _leftSplitterLockRight = -1;


        // Stop moving the splitter if the user tries to move it before the left splitter
        if (_splitContainer.left() <= (_middlePanel.left() + _middlePanMinWidth + _middlePanel.widthEx()) && _rightSplitterLockLeft == -1) {
            _splitContainer.element.style.left = (_middlePanel.left() + _middlePanMinWidth + _splitContainer.widthT()) + 'px';
            _rightSplitterLockLeft = _splitContainer.left();
            _rightSplitterLockRight = -1;
        }
        // Stops the splitter moving past the right panels min width
        else if ((_splitContainer.left() + _splitContainer.widthT() >= _currentBodyWidth - (_rightPanMinWidth + _rightPanel.widthEx())) && _rightSplitterLockRight == -1) {
            //_splitContainer.element.style.left = (_rightPanel.left() - _splitContainer.widthT()) + 'px';
            _splitContainer.element.style.left = _currentBodyWidth - (_rightPanMinWidth + _rightPanel.widthEx() + _splitContainer.widthT()) + 'px';
            _rightSplitterLockRight = _splitContainer.left();
            _rightSplitterLockLeft = -1;
        }
        else if (_rightSplitterLockLeft != -1 && currentmouseX > _rightSplitterLockLeft) {
            _leftSplitterLockLeft = -1;
            _splitContainer.element.style.left = currentmouseX + _mouseOffSetX + 'px';
        }
        else if (_rightSplitterLockLeft != -1 && currentmouseX < _rightSplitterLockLeft) {
            // Do nothing so the splitter stops moving.
        }
        else if (_rightSplitterLockRight != -1 && currentmouseX < _rightSplitterLockRight) {
            _rightSplitterLockRight = -1;
            _splitContainer.element.style.left = currentmouseX + _mouseOffSetX + 'px';
        }
        else if (_rightSplitterLockRight != -1 && currentmouseX > _rightSplitterLockRight) {
            // Do nothing so the splitter stops moving.
        }
        else {
            _splitContainer.element.style.left = currentmouseX + _mouseOffSetX + 'px';
        }

        // Make sure the new widths are not less than it should be.
        // putting this in stops IE8 from crashing when moving the right splitter at a extremely fast rate.

        var rightPanelLeft;
        var rightPanelWidth;
        var newMiddlePanWidth = _splitContainer.left() - _middlePanel.left() - _middlePanel.widthEx();

        if (newMiddlePanWidth >= _middlePanMinWidth)
            _middlePanel.element.style.width = (newMiddlePanWidth) + 'px';
        else
            _middlePanel.element.style.width = _middlePanMinWidth + 'px';

        rightPanelLeft = _splitContainer.left() + _splitContainer.widthT();
        rightPanelWidth = _currentBodyWidth - rightPanelLeft - _rightPanel.widthEx();

        if (rightPanelWidth < _rightPanMinWidth) rightPanelWidth = _rightPanMinWidth;

        if ((rightPanelWidth + rightPanelLeft + _rightPanel.widthEx()) > _currentBodyWidth) {
            _rightPanel.element.style.left = rightPanelLeft + 'px';
            _rightPanel.element.style.width = rightPanelWidth + 'px';
        }
        else {
            _rightPanel.element.style.width = rightPanelWidth + 'px';
            _rightPanel.element.style.left = rightPanelLeft + 'px';
        }
    }

    OrganiseTabs();
    StopFurtherAction(e);
}

function StopFurtherAction(e) {
    if (IE) {
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }
    else {
        e.preventDefault();
    }
}

function ResizeDisplay() {

    var leftPanelWithTemp;
    var middlePanelwidthTemp;
    var rightPanelwidthTemp;

    _currentBodyWidth = document.body.offsetWidth;

    if (_currentBodyWidth < 500)
        _currentBodyWidth = 500;

    _currentBodyHeight = document.body.offsetHeight;

    if (_currentBodyHeight < 500)
        _currentBodyHeight = 500;

    //The first time the page loads we set up a 20/60/20 split.
    if (_firstLoad) {

        // Get Ideal width for each column
        leftPanelWithTemp = Math.floor(((_currentBodyWidth / 100) * 20));
        middlePanelwidthTemp = Math.floor(((_currentBodyWidth / 100) * 60));
        rightPanelwidthTemp = Math.floor(((_currentBodyWidth / 100) * 20));

        // Find Additonal widths on each column and minus them from the ideal width
        // So for example column width should be 50px and its additional widths including all padding is 10 then we minus 10 from 50.
        leftPanelWithTemp = leftPanelWithTemp - _leftPanel.widthEx();
        middlePanelwidthTemp = middlePanelwidthTemp - _middlePanel.widthEx();
        rightPanelwidthTemp = rightPanelwidthTemp - _rightPanel.widthEx();

        // Sets the widths of the pannels
        _leftPanel.element.style.width = (leftPanelWithTemp - (_leftSplitter.widthT() / 2)) + 'px';
        _middlePanel.element.style.width = (middlePanelwidthTemp - _leftSplitter.widthT()) + 'px';
        _rightPanel.element.style.width = (rightPanelwidthTemp - (_leftSplitter.widthT() / 2)) + 'px';

        // Sets the possitions of each pannel and splitter.
        _leftPanel.element.style.left = '0px';
        _leftSplitter.element.style.left = (_leftPanel.left() + _leftPanel.widthT()) + 'px';
        _middlePanel.element.style.left = (_leftSplitter.left() + _leftSplitter.widthT()) + 'px';
        _rightSplitter.element.style.left = (_middlePanel.left() + _middlePanel.widthT()) + 'px';
        _rightPanel.element.style.left = (_rightSplitter.left() + _rightSplitter.widthT()) + 'px';

        // test the size of the page just incase we had a odd total monitor width. this is because we cant use half a pixle.
        var tempWidth = leftPanelWithTemp + middlePanelwidthTemp + rightPanelwidthTemp + _leftSplitter.widthT() + _rightSplitter.widthT();

        // Resize for a perfect fit if required.
        if (tempWidth < _currentBodyWidth)
            _rightPanel.element.style.width = (_rightPanel.width() - (_currentBodyWidth - tempWidth)) + 'px';
        else (tempWidth > _currentBodyWidth)
        _rightPanel.element.style.width = (_rightPanel.width() - (tempWidth - _currentBodyWidth)) + 'px';

        _firstLoad = false;

    }
    else {

        //Get the total width of all the pannels and splitters - leaving out the middle Pannel
        var tempWidth = _leftPanel.widthT() + _leftSplitter.widthT() + _rightSplitter.widthT() + _rightPanel.widthT();

        // Set the middle pannel to fill the gap from teh above calculation.
        middlePanelwidthTemp = (_currentBodyWidth - tempWidth) - _middlePanel.widthEx();

        // The right splitter and panel will need to move because the middle panel will be resizing.
        var rightSplitterX = _middlePanel.width() + _middlePanel.left();
        var rightPannelX = rightSplitterX + _rightSplitter.width();

        // Find the new total width of the pannels and splitters.
        var totalWidth = middlePanelwidthTemp + _rightSplitter.widthT() + _rightPanel.widthT() + _middlePanel.left() + _middlePanel.widthEx();

        // Find any over or under pixles from the new width.
        var widthCorrection = _currentBodyWidth - totalWidth

        // If there is any correction needed remove or add it to the middle pannel.
        middlePanelwidthTemp += widthCorrection - _middlePanel.widthEx();

        // Dont let the middle pannel get smaller that 200 pixles.
        if (middlePanelwidthTemp < 200)
            middlePanelwidthTemp = 200;

        // Move the pannels and splitters
        _middlePanel.element.style.width = middlePanelwidthTemp + 'px';
        _rightSplitter.element.style.left = (_middlePanel.left() + _middlePanel.widthT()) + 'px';
        _rightPanel.element.style.left = (_rightSplitter.left() + _rightSplitter.widthT()) + 'px';

    }

    var toolBarTop = _toolBar.top();
    var toolBarH = _toolBar.height();
    var middlePanelH;
    var tabContainerH = _tabManager.container.heightT();

    _leftPanel.element.style.height = (_currentBodyHeight - toolBarTop - toolBarH - _leftPanel.heightEx()) + 'px';
    _leftSplitter.element.style.height = (_currentBodyHeight - toolBarTop - toolBarH - _leftSplitter.heightEx()) + 'px';
    _middlePanel.element.style.height = (_currentBodyHeight - toolBarTop - toolBarH - _middlePanel.heightEx()) + 'px';
    _rightSplitter.element.style.height = (_currentBodyHeight - toolBarTop - toolBarH - _rightSplitter.heightEx()) + 'px';
    _rightPanel.element.style.height = (_currentBodyHeight - toolBarTop - toolBarH - _rightPanel.heightEx()) + 'px';

    _leftPanel.element.style.top = (toolBarTop + toolBarH) + 'px';
    _leftSplitter.element.style.top = (toolBarTop + toolBarH) + 'px';
    _middlePanel.element.style.top = (toolBarTop + toolBarH) + 'px';
    _rightSplitter.element.style.top = (toolBarTop + toolBarH) + 'px';
    _rightPanel.element.style.top = (toolBarTop + toolBarH) + 'px';

    middlePanelH = _middlePanel.heightT();

    _viewerTabPage.element.style.height = (middlePanelH - tabContainerH - _viewerTabPage.widthEx()) + 'px';

    OrganiseTabs();
}

function OrganiseTabs() {
    _tabManager.reDraw();
}

function getCurrentStyle(obj, cssStyle, jsStyle) {
    // IE and FF use diffrent ways to retreaive the current style of elements on the page.

    var tempProperty;
    try {
        tempProperty = getComputedStyle(obj, null).getPropertyValue(cssStyle);
    } catch (e) {
        tempProperty = obj.currentStyle.getAttribute(jsStyle);
    }

    if (tempProperty != '')
        return parseInt(tempProperty);
    else
        return 0;
}

function TreeViewManager(container) {
    var _firstDropDownIndex = -1;
    var _treeViewManager = this;

    this.collapse = '/images/treeview/collapse.png';
    this.expand = '/images/treeview/expand.png';
    this.joinNode = '/images/treeview/joinNode_black.png';
    this.lastNode = '/images/treeview/lastNode_black.png';
    this.flowNode = '/images/treeview/flowNode_black.png';

    this.rootNodes = new Array();

    this.treeView = new Element(document.createElement('ul'), 'treeView');

    this.container = new Element(container, 'treeViewContainer');
    this.container.element.innerHTML = '';
    this.container.element.appendChild(this.treeView.element);

    this.addRootNodes = function (newTreeNode) {
        newTreeNode.owner = this;
        newTreeNode.SetManager(this);
        newTreeNode.SetupNode();
        _eventUtil.addEventHandler(newTreeNode.listItem.element, 'click', newTreeNode.SelectEvent);
        this.rootNodes.push(newTreeNode);
        this.treeView.element.appendChild(newTreeNode.listItem.element);

        newTreeNode.RedrawRootNode();
    }

    this.reDrawTreeView = function () {
        for (var i = 0; i < this.rootNodes.length; i++) {
            this.rootNodes[i].RedrawRootNode();
        }
    }

    this.formatToTreeView = function (xmlDoc) {
        if (xmlDoc.treeView.node) {
            for (var i = 0; i < xmlDoc.treeView.node.length; i++) {
                siteManagerTreeView.addRootNodes(formatNode(xmlDoc.treeView.node[i]));
            }
        }
    }

    var formatNode = function (xmlNode) {
        var newTreeNode = new treeNode(xmlNode.type, xmlNode.name, xmlNode.id);

        if (xmlNode.node) {
            for (var i = 0; i < xmlNode.node.length; i++) {
                newTreeNode.addNode(formatNode(xmlNode.node[i]));
            }
        }
        return newTreeNode;
    }

    this.dispose = function () {
        var treeViewManager = _treeViewManager;
        for (var i = 0; i < treeViewManager.rootNodes.length; i++) {
            treeViewManager.rootNodes[i].dispose();
        }

        treeViewManager.container.removeElement();

        DisposeObj(treeViewManager);
    }
}

function treeNode(type, text, id) {
    var _treeNode = this;
    var _manager;

    var _nodeImageTypeHolder = document.createElement('span');
    var _icon = document.createElement('img');
    var _displayText = document.createElement('span');
    var _stateImage = document.createElement('img');
    var _posImage = document.createElement('img');

    this.id = id;
    this.type = type;
    this.text = text;
    this.owner = null;
    this.opened = false;
    this.childList = new Element(document.createElement('ul'), 'treeNodeChildren');
    this.listItem = new Element(document.createElement('li'), 'treeNode');
    this.childNodes = new Array();
    this.openNodesCount = 0;
    this.page;

    _nodeImageTypeHolder.className = 'nodeImgType';

    _posImage.className = 'nodePosImg';

    _stateImage.className = 'nodeStateImg';

    _nodeImageTypeHolder.appendChild(_posImage);
    _nodeImageTypeHolder.appendChild(_stateImage);

    _icon.className = 'nodeIconImg';

    this.listItem.element.appendChild(_nodeImageTypeHolder);
    this.listItem.element.appendChild(_icon);
    this.listItem.element.appendChild(_displayText);
    this.listItem.element.appendChild(this.childList.element);

    this.listItem.element.className = 'treeNode';

    this.childList.element.className = '';

    this.setPage = function () {
        this.page = new Page(this.type, this.id);
        this.page.owner = this;
    }

    this.treeNodeClass = function (classNames) {
        this.listItem.element.className = classNames;
    }

    this.SetManager = function (newManager) {
        _manager = newManager;

        for (var i = 0; i < this.childNodes.length; i++) {
            this.childNodes[i].SetManager(_manager);
        }
    }

    this.addNode = function (newNode) {
        newNode.owner = this;
        newNode.SetupNode();
        _eventUtil.addEventHandler(newNode.listItem.element, 'click', newNode.SelectEvent);
        this.AddChildNode(newNode);
    }

    this.AddChildNode = function (newNode) {
        this.childNodes.push(newNode);
        this.childList.element.appendChild(newNode.listItem.element);
    }

    this.SetHolderHeight = function (newHeight) {
        _nodeImageTypeHolder.style.height = newHeight + 'px';
    }

    this.RedrawRootNode = function () {
        this.RedrawNodes();
        this.openNodesCount = this.GetOpenNodes(this);

        var rootNodeIndex = _manager.rootNodes.indexOf(this);

        if (rootNodeIndex > 0) {
            _manager.rootNodes[rootNodeIndex - 1].SetHolderHeight((_manager.rootNodes[rootNodeIndex - 1].openNodesCount) * _treeViewListItemHeight);
            _manager.rootNodes[rootNodeIndex - 1].SetJoinNode();
        }

        this.SetLastNode();
    }

    this.SetJoinNode = function () {
        _posImage.src = _manager.joinNode
    }

    this.SetLastNode = function () {
        _posImage.src = _manager.lastNode;
    }

    this.RedrawNodes = function () {
        if (this.childNodes.length > 0) {
            if (this.opened)
                this.openChildren();
            else
                this.closeChildren();

            _posImage.src = _manager.joinNode;

            for (var i = 0; i < this.childNodes.length; i++) {
                this.childNodes[i].RedrawNodes();
            }

            this.childNodes[this.childNodes.length - 1].SetLastNode();
        }
        else {
            _posImage.src = _manager.joinNode;

            for (var n = 0; n < _nodeImageTypeHolder.childNodes.length; n++) {
                if (_nodeImageTypeHolder.childNodes[n] == _stateImage)
                    _nodeImageTypeHolder.removeChild(_stateImage);
            }
        }
    }

    this.GetOpenNodes = function (node) {
        var openNodes = 1;

        if (node.childNodes.length > 0 && node.opened) {
            for (var i = 0; i < node.childNodes.length; i++) {
                openNodes += this.GetOpenNodes(node.childNodes[i]);

                if (node.childNodes.indexOf(node.childNodes[i]) > 0)
                    node.childNodes[i - 1].SetHolderHeight(node.childNodes[i - 1].openNodesCount * _treeViewListItemHeight);
            }
        }

        node.openNodesCount = openNodes;
        return openNodes;
    }

    this.openChildren = function () {
        _stateImage.src = _manager.collapse;
        this.childList.element.style.display = 'block';
    }
    this.closeChildren = function () {
        _stateImage.src = _manager.expand;
        this.childList.element.style.display = 'none';
    }

    this.SelectEvent = function (e) {
        var treeNode = _treeNode;
        treeNode.Open();
        if (e.stopPropagation) { e.stopPropagation(); }
        StopFurtherAction(e);
    }

    this.Open = function () {

        switch (this.type) {
            case "basepage":
            case "template":
            case "csssnippet":
                _tabManager.addTab(this.id, this.type, this.text, this);
            default:
                if (this.opened) {
                    this.opened = false;
                }
                else {
                    this.opened = true;
                }

                _manager.reDrawTreeView();
                break;
        }

    }

    this.SetType = function (newType) {
        var iconName = '';

        this.type = newType;

        switch (this.type) {
            case "site":
                iconName = "page_html.gif";
                break;
            case "page":
                iconName = "page_offline.gif";
                break;
            case "basepage":
                iconName = "page_online.gif";
                break;
        }

        _icon.src = 'images/' + iconName;

        if (iconName == '') {
            this.listItem.element.removeChild(_icon);
            _displayText.className = 'noImg';
        }
    }
    this.SetText = function (newText) {
        this.text = newText
        _displayText.innerHTML = this.text;
    }
    this.SetId = function (newId) {
        this.id = newId;

        if (this.owner != undefined && this.owner.id != undefined)
            this.listItem.element.id = '$$TreeNode$$' + this.owner.id + this.id;
        else
            this.listItem.element.id = '$$TreeNode$$' + this.id;
    }

    this.SetupNode = function () {
        this.SetText(this.text);
        this.SetType(this.type);
        this.SetId(this.id);
        this.setPage();
    }

    this.dispose = function () {
        var treeNode = _treeNode;
        for (var i = 0; i < treeNode.childNodes.length; i++) {
            treeNode.childNodes[i].dispose;
        }

        treeNode.page.dispose();

        _eventUtil.removeEventHandler(treeNode.listItem.element, 'click', treeNode.SelectEvent);

        treeNode.listItem.removeElement();

        DisposeObj(treeNode);
    }
}




function encodeForm(toEncode) {
    var formInputs = toEncode.split(';');
    var tempArray = new Array();

    for (var i = 0; i < formInputs.length; i++) {
        tempArray[i] = document.getElementById(formInputs[i]).value.replace(/</g, '[LT]');
    }

    for (var i = 0; i < tempArray.length; i++) {
        document.getElementById(formInputs[i]).value = tempArray[i];
    }

    return true;
}

function LoadDocType() {
    LoadFeed('/runjob.aspx?job=load-docTypes', '', '', DocTypesLoaded);
}

function DocTypesLoaded(XMLDoc, ElementID) {
    var docTypes = XMLDoc.docTypes.type;
    var docTypeComboBox = document.getElementById('basepagePageVersionSetup').getElementsByTagName('select')[0];

    docTypeComboBox.innerHTML = ""

    for (var i = 0; i < docTypes.length; i++) {
        var newOpt = new Option(docTypes[i].enumName, docTypes[i].enumNum);
        docTypeComboBox.options[i] = newOpt;
    }
}